 #include "Serializer.h"
#include <cstring>
#include <stdexcept>

namespace SeanNetwork {

Serializer::Serializer() : m_ReadPos(0), m_WritePos(0) {
    // 初始化空缓冲区
}

Serializer::Serializer(const uint8_t* data, size_t size) : m_ReadPos(0), m_WritePos(size) {
    /* 功能：从现有数据创建反序列化缓冲区
       参数：data-二进制数据，size-数据长度 */
    if (data != nullptr && size > 0) {
        m_Buffer.resize(size);
        std::memcpy(m_Buffer.data(), data, size);
    }
}

Serializer::Serializer(const std::vector<uint8_t>& data) : m_ReadPos(0), m_WritePos(data.size()) {
    m_Buffer = data;
}

Serializer::~Serializer() {
    // 显式清除缓冲区
    m_Buffer.clear();
}

void Serializer::Reset() {
    m_Buffer.clear();
    m_ReadPos = 0;
    m_WritePos = 0;
}

void Serializer::EnsureSpace(size_t additionalSize) {
    /* 功能：确保缓冲区有足够的空间写入数据
       参数：additionalSize-额外需要的字节数 */
    if (m_WritePos + additionalSize > m_Buffer.size()) {
        m_Buffer.resize(m_WritePos + additionalSize);
    }
}

// 基本类型写入
void Serializer::Write(bool value) {
    uint8_t v = value ? 1 : 0;
    Write(v);
}

void Serializer::Write(int8_t value) {
    EnsureSpace(sizeof(value));
    m_Buffer[m_WritePos++] = static_cast<uint8_t>(value);
}

void Serializer::Write(uint8_t value) {
    EnsureSpace(sizeof(value));
    m_Buffer[m_WritePos++] = value;
}

void Serializer::Write(int16_t value) {
    EnsureSpace(sizeof(value));
    uint16_t nvalue = HostToNetwork(static_cast<uint16_t>(value));
    std::memcpy(&m_Buffer[m_WritePos], &nvalue, sizeof(nvalue));
    m_WritePos += sizeof(nvalue);
}

void Serializer::Write(uint16_t value) {
    EnsureSpace(sizeof(value));
    uint16_t nvalue = HostToNetwork(value);
    std::memcpy(&m_Buffer[m_WritePos], &nvalue, sizeof(nvalue));
    m_WritePos += sizeof(nvalue);
}

void Serializer::Write(int32_t value) {
    EnsureSpace(sizeof(value));
    uint32_t nvalue = HostToNetwork(static_cast<uint32_t>(value));
    std::memcpy(&m_Buffer[m_WritePos], &nvalue, sizeof(nvalue));
    m_WritePos += sizeof(nvalue);
}

void Serializer::Write(uint32_t value) {
    EnsureSpace(sizeof(value));
    uint32_t nvalue = HostToNetwork(value);
    std::memcpy(&m_Buffer[m_WritePos], &nvalue, sizeof(nvalue));
    m_WritePos += sizeof(nvalue);
}

void Serializer::Write(int64_t value) {
    EnsureSpace(sizeof(value));
    uint64_t nvalue = HostToNetwork(static_cast<uint64_t>(value));
    std::memcpy(&m_Buffer[m_WritePos], &nvalue, sizeof(nvalue));
    m_WritePos += sizeof(nvalue);
}

void Serializer::Write(uint64_t value) {
    EnsureSpace(sizeof(value));
    uint64_t nvalue = HostToNetwork(value);
    std::memcpy(&m_Buffer[m_WritePos], &nvalue, sizeof(nvalue));
    m_WritePos += sizeof(nvalue);
}

void Serializer::Write(float value) {
    EnsureSpace(sizeof(value));
    std::memcpy(&m_Buffer[m_WritePos], &value, sizeof(value));
    m_WritePos += sizeof(value);
}

void Serializer::Write(double value) {
    EnsureSpace(sizeof(value));
    std::memcpy(&m_Buffer[m_WritePos], &value, sizeof(value));
    m_WritePos += sizeof(value);
}

void Serializer::Write(const std::string& value) {
    /* 功能：序列化字符串
       参数：value-字符串值
       格式：先写入长度，再写入内容 */
    uint32_t length = static_cast<uint32_t>(value.length());
    Write(length);
    
    if (length > 0) {
        EnsureSpace(length);
        std::memcpy(&m_Buffer[m_WritePos], value.data(), length);
        m_WritePos += length;
    }
}

void Serializer::WriteBytes(const uint8_t* data, size_t size) {
    /* 功能：序列化二进制数据
       参数：data-二进制数据，size-数据长度
       格式：先写入长度，再写入内容 */
    uint32_t length = static_cast<uint32_t>(size);
    Write(length);
    
    if (length > 0 && data != nullptr) {
        EnsureSpace(length);
        std::memcpy(&m_Buffer[m_WritePos], data, length);
        m_WritePos += length;
    }
}

void Serializer::WriteBytes(const std::vector<uint8_t>& data) {
    WriteBytes(data.data(), data.size());
}

// 基本类型读取
bool Serializer::ReadBool() {
    return ReadUInt8() != 0;
}

int8_t Serializer::ReadInt8() {
    if (!CanRead(sizeof(int8_t))) {
        throw std::runtime_error("Not enough data to read Int8");
    }
    return static_cast<int8_t>(m_Buffer[m_ReadPos++]);
}

uint8_t Serializer::ReadUInt8() {
    if (!CanRead(sizeof(uint8_t))) {
        throw std::runtime_error("Not enough data to read UInt8");
    }
    return m_Buffer[m_ReadPos++];
}

int16_t Serializer::ReadInt16() {
    if (!CanRead(sizeof(int16_t))) {
        throw std::runtime_error("Not enough data to read Int16");
    }
    
    uint16_t value;
    std::memcpy(&value, &m_Buffer[m_ReadPos], sizeof(value));
    m_ReadPos += sizeof(value);
    return static_cast<int16_t>(NetworkToHost(value));
}

uint16_t Serializer::ReadUInt16() {
    if (!CanRead(sizeof(uint16_t))) {
        throw std::runtime_error("Not enough data to read UInt16");
    }
    
    uint16_t value;
    std::memcpy(&value, &m_Buffer[m_ReadPos], sizeof(value));
    m_ReadPos += sizeof(value);
    return NetworkToHost(value);
}

int32_t Serializer::ReadInt32() {
    if (!CanRead(sizeof(int32_t))) {
        throw std::runtime_error("Not enough data to read Int32");
    }
    
    uint32_t value;
    std::memcpy(&value, &m_Buffer[m_ReadPos], sizeof(value));
    m_ReadPos += sizeof(value);
    return static_cast<int32_t>(NetworkToHost(value));
}

uint32_t Serializer::ReadUInt32() {
    if (!CanRead(sizeof(uint32_t))) {
        throw std::runtime_error("Not enough data to read UInt32");
    }
    
    uint32_t value;
    std::memcpy(&value, &m_Buffer[m_ReadPos], sizeof(value));
    m_ReadPos += sizeof(value);
    return NetworkToHost(value);
}

int64_t Serializer::ReadInt64() {
    if (!CanRead(sizeof(int64_t))) {
        throw std::runtime_error("Not enough data to read Int64");
    }
    
    uint64_t value;
    std::memcpy(&value, &m_Buffer[m_ReadPos], sizeof(value));
    m_ReadPos += sizeof(value);
    return static_cast<int64_t>(NetworkToHost(value));
}

uint64_t Serializer::ReadUInt64() {
    if (!CanRead(sizeof(uint64_t))) {
        throw std::runtime_error("Not enough data to read UInt64");
    }
    
    uint64_t value;
    std::memcpy(&value, &m_Buffer[m_ReadPos], sizeof(value));
    m_ReadPos += sizeof(value);
    return NetworkToHost(value);
}

float Serializer::ReadFloat() {
    if (!CanRead(sizeof(float))) {
        throw std::runtime_error("Not enough data to read Float");
    }
    
    float value;
    std::memcpy(&value, &m_Buffer[m_ReadPos], sizeof(value));
    m_ReadPos += sizeof(value);
    return value;
}

double Serializer::ReadDouble() {
    if (!CanRead(sizeof(double))) {
        throw std::runtime_error("Not enough data to read Double");
    }
    
    double value;
    std::memcpy(&value, &m_Buffer[m_ReadPos], sizeof(value));
    m_ReadPos += sizeof(value);
    return value;
}

std::string Serializer::ReadString() {
    /* 功能：反序列化字符串
       返回：解析出的字符串值 */
    uint32_t length = ReadUInt32();
    if (length == 0) {
        return std::string();
    }
    
    if (!CanRead(length)) {
        throw std::runtime_error("Not enough data to read String");
    }
    
    std::string result(reinterpret_cast<char*>(&m_Buffer[m_ReadPos]), length);
    m_ReadPos += length;
    return result;
}

std::vector<uint8_t> Serializer::ReadBytes(size_t size) {
    /* 功能：读取指定长度的二进制数据
       参数：size-要读取的字节数
       返回：读取的二进制数据 */
    if (!CanRead(size)) {
        throw std::runtime_error("Not enough data to read Bytes");
    }
    
    std::vector<uint8_t> result(size);
    if (size > 0) {
        std::memcpy(result.data(), &m_Buffer[m_ReadPos], size);
        m_ReadPos += size;
    }
    return result;
}

// 网络字节序转换
template<typename T>
T Serializer::NetworkToHost(T value) {
    /* 功能：网络字节序转主机字节序
       参数：value-网络字节序的值
       返回：主机字节序的值 */
    if constexpr (sizeof(T) == 1) {
        return value;
    }
    else if constexpr (sizeof(T) == 2) {
        return static_cast<T>((value >> 8) | (value << 8));
    }
    else if constexpr (sizeof(T) == 4) {
        return static_cast<T>(
            ((value & 0x000000FF) << 24) |
            ((value & 0x0000FF00) << 8) |
            ((value & 0x00FF0000) >> 8) |
            ((value & 0xFF000000) >> 24)
        );
    }
    else if constexpr (sizeof(T) == 8) {
        return static_cast<T>(
            ((value & 0x00000000000000FFULL) << 56) |
            ((value & 0x000000000000FF00ULL) << 40) |
            ((value & 0x0000000000FF0000ULL) << 24) |
            ((value & 0x00000000FF000000ULL) << 8) |
            ((value & 0x000000FF00000000ULL) >> 8) |
            ((value & 0x0000FF0000000000ULL) >> 24) |
            ((value & 0x00FF000000000000ULL) >> 40) |
            ((value & 0xFF00000000000000ULL) >> 56)
        );
    }
    else {
        static_assert(sizeof(T) <= 8, "Unsupported type size");
        return value;
    }
}

template<typename T>
T Serializer::HostToNetwork(T value) {
    // 网络字节序是大端，与主机转网络相同的实现
    return NetworkToHost(value);
}

// 显式实例化模板函数，避免链接错误
template uint16_t Serializer::NetworkToHost<uint16_t>(uint16_t);
template uint32_t Serializer::NetworkToHost<uint32_t>(uint32_t);
template uint64_t Serializer::NetworkToHost<uint64_t>(uint64_t);
template uint16_t Serializer::HostToNetwork<uint16_t>(uint16_t);
template uint32_t Serializer::HostToNetwork<uint32_t>(uint32_t);
template uint64_t Serializer::HostToNetwork<uint64_t>(uint64_t);

} // namespace SeanNetwork
